<?php

namespace addons\cmstostatic\controller;

use addons\cms\model\Channel;
use addons\cms\model\Archives;
use addons\cmstostatic\library\Generator;
use addons\cmstostatic\model\Cmstostaticpaths;
use think\addons\Controller;
use think\Db;


class Generate extends Controller
{
    /**
     * 默认访问方法
     */
    public function index()
    {
        $this->error("当前插件暂无前台页面");
    }

    /**
     * 生成首页
     * @return \think\response\Json
     */
    public function home()
    {
        if ($this->request->isAjax()) {
            $generator = new Generator();
            $generateResult = $generator->home();
            $staticConfig = get_addon_config('cmstostatic');

            $platform = '电脑版';
            $url = addon_url('cms/index/index') . $staticConfig['home_default'];
            if(!empty($staticConfig['mobile_on'])){ // 手机版路径
                $url = '/' . $staticConfig['mobile_path'] . $url;
                $platform = '手机版';
            }

            $step = 1;
            $total = 1;
            $msg = '正在生成' . $platform . '首页静态文件';
            $desc = '成功生成' . $platform . '首页静态文件：[<a href="' . $url . '" target="_blank" >查看' . $platform . '首页</a>]';

            $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);

            return json($response);
        }

        $this->error("错误的访问方式");
    }

    /**
     * 生成栏目页
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function channel(){
        if ($this->request->isAjax()) {
            // 获取参数
            $channel_id = $this->request->param('channel', 0);
            $isson      = $this->request->param('isson', 0);
            $step       = $this->request->param('step', 0);

            $staticConfig = get_addon_config('cmstostatic');
            $dataIndex = $step;
            $dataSet = [];
            $total = 0;
            $channelName = '';
            $msg = '';
            $desc = '';

            // 有channel_id
            if(!empty($channel_id)){
                // 是否只生成自己
                if(!empty($isson)){
                    $dataSet = [$channel_id];
                    $total = 1;
                }
                else{
                    $dataSet = Channel::getChannelChildrenIds($channel_id);
                    $total = count($dataSet);
                }
            }
            else{
                // $dataSet = Collection(Channel::all())->toArray();
                $dataSet = Channel::where([])->column('id');
                $total = Channel::count();
            }

            // 栏目数据不能为空
            if(!empty($dataSet)){

                // 不存在栏目数据
                if(!isset($dataSet[$dataIndex])){
                    $msg = '栏目数据出错，请在CMS系统中检查栏目！';
                    $desc = '栏目数据出错，请刷新重试！';
                    $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);

                    return json($response);
                }

                $generator = new Generator();
                $generateResult = $generator->channel($dataSet[$dataIndex]);
                $channelName = Channel::where(['id'=>$dataSet[$dataIndex]])->value('name');
                $channelUrl = $generator->getChannelUrl($dataSet[$dataIndex]);

                $step++; // 步进增加
                $progressbarPercent = $total > 0 ? ceil($step / $total * 100) : 0;

                $platform = '电脑版';
                if(!empty($staticConfig['mobile_on'])){ // 手机版路径
                    $platform = '手机版';
                }

                $msg = '正在生成' . $platform . '栏目静态文件：已完成' . $progressbarPercent . '%';
                $desc = '成功生成' . $platform . '栏目[' . $dataSet[$dataIndex] . ']：[<a href="' . $channelUrl . '" target="_blank" >' . $channelName . '</a>]';

                // 跳转栏目提示
                if('redirect' === $generateResult){
                    $desc = '跳转栏目无需生成[' . $dataSet[$dataIndex] . ']：[<a href="' . $channelUrl . '" target="_blank" >' . $channelName . '</a>]';
                }

                $response = array("code"=>1, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
                if($step >= $total){
                    $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
                }
            }
            else{
                $msg = '栏目数据为空，请在CMS系统中添加栏目！';
                $desc = '栏目数据为空，无需生成！';
                $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
            }

            return json($response);
        }

        $this->error("错误的访问方式");
    }

    /**
     * 生成文章页
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function article(){
        if ($this->request->isAjax()) {
            // 获取参数
            $channel_id = $this->request->param('channel', 0);
            $isson      = $this->request->param('isson', 0);
            $step       = $this->request->param('step', 0);

            $staticConfig = get_addon_config('cmstostatic');
            $dataIndex = $step;
            $dataSet = [];
            $total = 0;
            $channelName = '';
            $msg = '';
            $desc = '';

            // 有channel_id
            if(!empty($channel_id)){
                // 是否只生成自己
                if(!empty($isson)){
                    $dataSet = Archives::where(['channel_id'=>$channel_id])->column('id');;
                    $total = count($dataSet);
                }
                else{
                    $childrenIds = Channel::getChannelChildrenIds($channel_id);
                    $dataSet = Archives::where('channel_id', 'in', $childrenIds)->column('id');;
                    $total = count($dataSet);
                }
            }
            else{
                // $dataSet = Collection(Archives::all())->toArray();
                $dataSet = Archives::where([])->column('id');
                $total = Archives::count();
            }


            // 栏目数据不能为空
            if(!empty($dataSet)){

                // 不存在栏目数据
                if(!isset($dataSet[$dataIndex])){
                    $msg = '文章数据出错，请在CMS系统中检查文章内容！';
                    $desc = '文章数据出错，请刷新重试！';
                    $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);

                    return json($response);
                }


                $generator = new Generator();
                $generateResult = $generator->article($dataSet[$dataIndex]);
                $articleTile = Archives::where(['id'=>$dataSet[$dataIndex]])->value('title');
                $articleUrl = $generator->getArticleUrl($dataSet[$dataIndex]);

                $step++; // 步进增加
                $progressbarPercent = $total > 0 ? ceil($step / $total * 100) : 0;

                $platform = '电脑版';
                if(!empty($staticConfig['mobile_on'])){ // 手机版路径
                    $platform = '手机版';
                }

                $msg = '正在生成' . $platform . '文章静态文件：已完成' . $progressbarPercent . '%';
                $desc = '成功生成' . $platform . '文章[' . $dataSet[$dataIndex] . ']：[<a href="' . $articleUrl . '" target="_blank" >' . $articleTile . '</a>]';

                // 跳转栏目提示
                if('redirect' === $generateResult){
                    $desc = '跳转文章无需生成[' . $dataSet[$dataIndex] . ']：[<a href="' . $articleUrl . '" target="_blank" >' . $articleTile . '</a>]';
                }

                $response = array("code"=>1, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
                if($step >= $total){
                    $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
                }
            }
            else{
                $msg = '文章数据为空，请在CMS系统中添加文章！';
                $desc = '文章数据为空，无需生成！';
                $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
            }

            return json($response);
        }

        $this->error("错误的访问方式");
    }


    /**
     * todo 可以增加按照新增内容生成或者日期时间生成
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function all()
    {
        if ($this->request->isAjax()) {
            // 获取参数
            $step = $this->request->param('step', 0);
            $isdel = $this->request->param('isdel', 0);

            if($isdel){
                return $this->delstatic($step);
            }

            $generator = new Generator();

            $dataSetChannel = Channel::where([])->column('id');
            $channelCount = Channel::count();

            $dataSetArticle = Archives::where([])->column('id');
            $articleCount = Archives::count();

            // 组织数据
            $staticConfig = get_addon_config('cmstostatic');
            $dataSet = array_merge([0], $dataSetChannel, $dataSetArticle);
            $total = $channelCount + $articleCount + 1;
            $dataIndex = $step;
            $msg = '';
            $desc = '';

            $platform = '电脑版';
            if(!empty($staticConfig['mobile_on'])){ // 手机版路径
                $platform = '手机版';
            }

            // 生成类型判断
            if(0 === $dataSet[$dataIndex]){
                $generateResult = $generator->home();
                $url = addon_url('cms/index/index') . $staticConfig['home_default'];
                if(!empty($staticConfig['mobile_on'])){ // 手机版路径
                    $url = '/' . $staticConfig['mobile_path'] . $url;
                }

                $step++; // 步进增加
                $msg = '正在生成' . $platform . '首页静态文件';
                $desc = '成功生成' . $platform . '首页静态文件：[<a href="' . $url . '" target="_blank" >查看' . $platform . '首页</a>]';
            }
            else if($dataIndex <= $channelCount){
                $generateResult = $generator->channel($dataSet[$dataIndex]);
                $channelName = Channel::where(['id'=>$dataSet[$dataIndex]])->value('name');
                $channelUrl = $generator->getChannelUrl($dataSet[$dataIndex]);

                $step++; // 步进增加
                $progressbarPercent = $total > 0 ? ceil($step / $total * 100) : 0;

                $msg = '正在生成' . $platform . '栏目静态文件：已完成' . $progressbarPercent . '%';
                $desc = '成功生成' . $platform . '栏目[' . $dataSet[$dataIndex] . ']：[<a href="' . $channelUrl . '" target="_blank" >' . $channelName . '</a>]';

                // 跳转栏目提示
                if('redirect' === $generateResult){
                    $desc = '跳转栏目无需生成[' . $dataSet[$dataIndex] . ']：[<a href="' . $channelUrl . '" target="_blank" >' . $channelName . '</a>]';
                }
            }
            else{
                $generateResult = $generator->article($dataSet[$dataIndex]);
                $articleTile = Archives::where(['id'=>$dataSet[$dataIndex]])->value('title');
                $articleUrl = $generator->getArticleUrl($dataSet[$dataIndex]);

                $step++; // 步进增加
                $progressbarPercent = $total > 0 ? ceil($step / $total * 100) : 0;

                $msg = '正在生成' . $platform . '文章静态文件：已完成' . $progressbarPercent . '%';
                $desc = '成功生成' . $platform . '文章[' . $dataSet[$dataIndex] . ']：[<a href="' . $articleUrl . '" target="_blank" >' . $articleTile . '</a>]';

                // 跳转栏目提示
                if('redirect' === $generateResult){
                    $desc = '跳转文章无需生成[' . $dataSet[$dataIndex] . ']：[<a href="' . $articleUrl . '" target="_blank" >' . $articleTile . '</a>]';
                }
            }


            $response = array("code"=>1, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
            if($step >= $total){
                $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
            }

            return json($response);
        }

        $this->error("错误的访问方式");
    }


    private function delstatic($index){

        $dataSet = Cmstostaticpaths::where([])->column('path');

        $step = $index;
        $total = count($dataSet);
        if(empty($total)){
            $msg = '没有静态文件，无需删除！';
            $desc = '没有静态文件，请先生成静态文件！';
            $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);

            return json($response);
        }

        // 删除文件
        $file_path = ROOT_PATH . $dataSet[$step];

        if(is_file($file_path)){
            if(is_writable($file_path)){
                $result = unlink($file_path);
                if($result){
                    $desc = '文件：[' . $file_path . '] 删除成功';
                }
                else{
                    $desc = '文件：[' . $file_path . '] 删除失败';
                }
            }
            else{
                $desc = '文件：[' . $file_path . '] 无法操作';
            }
        }
        else{
            $desc = '文件：[' . $file_path . '] 不存在';
        }

        $step++; // 步进增加
        $progressbarPercent = $total > 0 ? ceil($step / $total * 100) : 0;
        $msg = '正在删除静态文件：已完成' . $progressbarPercent . '%';


        $response = array("code"=>1, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
        if($step >= $total){
            // TODO 删除成功后续操作 清空路径表
            // 删除为空目录
            $dirs = [];
            foreach($dataSet as $item){
                $dirs[] = dirname(ROOT_PATH . $item);
            }
            $dirs = array_unique($dirs);
            foreach($dirs as $dir){
                if(is_dir($dir)){
                    if(!(new \FilesystemIterator($dir))->valid()){
                        rmdir($dir);
                    }
                }
            }

            // 清空路径数据表
            Db::execute("TRUNCATE " . config('database.prefix') . "cmstostatic_paths;");

            $response = array("code"=>0, "msg"=>$msg, "data"=>"", "url"=>"", "wait"=>"", "total" => $total, "step" => $step, "desc"=>$desc);
        }

        return json($response);
    }
}
